package cn.whit.blog.service.impl;

import java.sql.SQLException;
import java.util.List;

import cn.whit.blog.dao.VoteDao;
import cn.whit.blog.dao.VoteItemDao;
import cn.whit.blog.domain.Vote;
import cn.whit.blog.domain.VoteItem;
import cn.whit.blog.service.VoteItemService;
import cn.whit.blog.util.BeanFactory;
import cn.whit.blog.util.DynamicQuery;
import cn.whit.blog.util.PageModel;

public class VoteItemServiceImpl implements VoteItemService {

	VoteItemDao voteItemDao = (VoteItemDao)BeanFactory.createObject("voteItemDao");
	
	VoteDao voteDao = (VoteDao)BeanFactory.createObject("voteDao");
	
	@Override
	public VoteItem findById(String id) throws SQLException {
		return voteItemDao.findById(id);
	}

	@Override
	public List<VoteItem> findAll() throws SQLException {
		return voteItemDao.findAll();
	}

	@Override
	public List<VoteItem> findAllWithPageAndQuery(int startIndex, int pageSize, DynamicQuery query) throws Exception {
		return voteItemDao.findAllWithPageAndQuery(startIndex, pageSize, query);
	}

	@Override
	public int findTotalRecordsAndQuery(DynamicQuery query) throws Exception {
		return voteItemDao.findTotalRecordsAndQuery(query);
	}

	@Override
	public void save(VoteItem voteItem) throws SQLException {
		voteItemDao.save(voteItem);
		//将投票对象中的小计数据增加1
		voteDao.addOptionNum(voteItem.getVoteid(),voteItem.getOptionid());
		
	}

	@Override
	public void update(VoteItem voteItem) throws SQLException {
		voteItemDao.update(voteItem);
	}

	@Override
	public PageModel findByPageAndQuery(int startIndex, int pageSize, DynamicQuery query) throws Exception {
		//startIndex 从第一页，索引 1 开始
		int totalRecords = voteItemDao.findTotalRecordsAndQuery(query);
		PageModel pm = new PageModel(startIndex,totalRecords,pageSize);
		List<VoteItem> list = voteItemDao.findAllWithPageAndQuery(pm.getStartIndex(),pm.getPageSize(),query);
		pm.setList(list);
		pm.setUrl("VoteServlet?method=list");
		return pm;
	}
	
	@Override
	public PageModel findByPageAndQuery2(int startIndex, int pageSize, DynamicQuery query) throws Exception {
		//startIndex 从第一页，索引 1 开始
		int totalRecords = voteItemDao.findTotalRecordsAndQuery(query);
		PageModel pm = new PageModel(startIndex,totalRecords,pageSize);
		List<VoteItem> list = voteItemDao.findAllWithPageAndQuery(pm.getStartIndex(),pm.getPageSize(),query);
		pm.setList(list);
		pm.setUrl("VoteServlet?method=voteList");
		return pm;
	}

	@Override
	public VoteItem getById(String id) throws SQLException {
		return voteItemDao.findById(id);
	}

	@Override
	public List<VoteItem> findByUserIdAndVoteId(String id, String voteid) throws SQLException {
		return voteItemDao.findByUserIdAndVoteId(id, voteid);
	}

}
